﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Kalficom.Forms
{
    public partial class frmContract_CreateModify : Form
    {
        public frmContract_CreateModify()
        {
            InitializeComponent();
            conf.Icon(this);
        }

        Libraies.db db = new Libraies.db();
        Query.qry_contract query = new Query.qry_contract();
        Libraies.msg msg = new Libraies.msg();
        bool _isCopy = false;

        private void frmContract_CreateModify_Load(object sender, EventArgs e)
        {
            // If form's Tag is null -> create new contract.
            // If from's Tag not null -> modify contract. (Tag is conf_id for modify)
            if (this.Tag != null)
            {
                btnCreate.Visible = true;
                db.FillDataSet(string.Format(query.get_where, this.Tag), tblContract);
                db.FillDataSet(string.Format(query.get_list_clientTaken, this.Tag), tblClientTaken);
            }

            db.FillDataSet(query.get_client, tblClient);

            // Enable the owner draw on the ComboBox.
            this.cboClientCode.DrawMode = DrawMode.OwnerDrawFixed;
            // Handle the DrawItem event to draw the items.
            this.cboClientCode.DrawItem += delegate(object cmb, DrawItemEventArgs args)
            {
                // Draw the default background
                args.DrawBackground();


                // The ComboBox is bound to a DataTable,
                // so the items are DataRowView objects.
                DataRowView drv = (DataRowView)this.cboClientCode.Items[args.Index];

                // Retrieve the value of each column.
                string id = drv["TX_CODE"].ToString();
                string name = drv["TX_NOM"].ToString();

                // Get the bounds for the first column
                Rectangle r1 = args.Bounds;
                r1.Width /= 3;

                // Draw the text on the first column
                using (SolidBrush sb = new SolidBrush(args.ForeColor))
                {
                    args.Graphics.DrawString(id, args.Font, sb, r1);
                }

                // Draw a line to isolate the columns 
                using (Pen p = new Pen(Color.Black))
                {
                    args.Graphics.DrawLine(p, r1.Right, 0, r1.Right, r1.Bottom);
                }

                // Get the bounds for the second column
                Rectangle r2 = args.Bounds;
                r2.X = (args.Bounds.Width / 3) +2;
                r2.Width /= 2;

                // Draw the text on the second column
                using (SolidBrush sb = new SolidBrush(args.ForeColor))
                {
                    args.Graphics.DrawString(name, args.Font, sb, r2);
                }
            };

            // Set Combobox Style
            (new Libraies.ctl()).ComboBox_Style(new ComboBox[] { cboClientCode });

            this.WindowState = FormWindowState.Maximized;
        }

        private void cboClientCode_SelectedIndexChanged(object sender, EventArgs e)
        {
            //bsClientInfo.Position = cboClientCode.SelectedIndex;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btnValidate_Click(object sender, EventArgs e)
        {
            // Check Identifiation blank field
            if (txtContCode.Text.Trim() == "")
            {
                MessageBox.Show(msg.cont_codeBlankMsg, msg.captionMsg, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                txtContCode.Focus();
                return;
            }

            if (cboClientCode.Text.Trim() == "")
            {
                MessageBox.Show(msg.cont_clientBlankMsg, msg.captionMsg, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                cboClientCode.Focus();
                return;
            }

          
            if (!(new Libraies.ctl()).check_ComboValue(new ComboBox[] { cboClientCode })) return;

            DataRow row = tblContract.NewRow();
            row["cont_number"] = txtContCode.Text;
            row["date_start"] = dtpContStart.Value.Date;
            row["date_end"] = dtpContEnd.Value.Date;
            row["client_to_invoice"] = cboClientCode.SelectedValue;
            row["active"] = chkActive.Checked;
            row["user_create"] = conf.CurUser;
            row["date_create"] = db.GetDate();

            // If form's Tag is null -> create new zone.
            // If from's Tag not null -> modify zone. (Tag is zone_id for modify)
            if (this.Tag == null)
            {

                // Check Identifiation dublicate field.
                if (db.ExecuteScalar(string.Format(query.scalarID, db.SqlString(txtContCode.Text))) != "")
                {
                    MessageBox.Show(msg.cont_codeExistMsg, msg.captionMsg, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    txtContCode.Focus();
                    return;
                }

                if (MessageBox.Show(msg.saveMsg, msg.captionMsg, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                {
                    // Add zone into database.
                    tblContract.Rows.Add(row);

                    db.CommandBuilder(string.Format(query.get_where, 0), tblContract);


                    this.Tag = db.ExecuteScalar(string.Format(query.scalarID, db.SqlString(txtContCode.Text)));
                    db.FillDataSet(string.Format(query.get_where, this.Tag), tblContract);
                    btnCreate.Visible = true;
                }
            }
            else
            {
                // Check Identifiation dublicate field.
                string cont_id = db.ExecuteScalar(string.Format(query.scalarID, db.SqlString(txtContCode.Text)));
                if (cont_id != "" && cont_id != tblContract.Rows[0]["cont_id"].ToString())
                {
                    MessageBox.Show(msg.cont_codeExistMsg, msg.captionMsg, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    txtContCode.Focus();
                    return;
                }

                if (MessageBox.Show(msg.saveMsg, msg.captionMsg, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                {
                    // Update contract into database.
                    row["cont_id"] = this.Tag;
                    tblContract.Rows[0].ItemArray = row.ItemArray;

                    db.CommandBuilder(string.Format(query.get_where, this.Tag), tblContract);
                }

            }
        }

        private void btnCreate_Click(object sender, EventArgs e)
        {
            Forms.frmClient_Taken frm = new Forms.frmClient_Taken();
            frm.cont_id = int.Parse(this.Tag.ToString());
            frm.TX_CODE = cboClientCode.SelectedValue.ToString();
            frm.ShowDialog();
            db.FillDataSet(string.Format(query.get_list_clientTaken, this.Tag), tblClientTaken);
        }

        private void dgClientTaken_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;
            Forms.frmClient_Taken frm = new Forms.frmClient_Taken();
            frm.cont_id = int.Parse(this.Tag.ToString());
            frm.Tag = dgClientTaken.Rows[e.RowIndex].Cells["client_taken_id"].Value;
            if (_isCopy) frm.client_id_copy = int.Parse(frm.Tag.ToString());

            frm.ShowDialog();
          
                // Read user record from database
                db.FillDataSet(string.Format(query.get_list_clientTaken, this.Tag), tblClientTaken);
                _isCopy = false;
           
        }

        private void dgClientTaken_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex == dgClientTaken.Columns["colDelete"].Index)
            {
                Libraies.msg msg = new Libraies.msg();
                if (MessageBox.Show(msg.deleteMsg, msg.captionMsg, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                {
                    // Delete zone from database.
                    db.ExecuteNonQuery(string.Format(query.del_clientTaken_Analyze, dgClientTaken.CurrentRow.Cells["client_taken_id"].Value));
                    db.ExecuteNonQuery(string.Format(query.del_clientTaken_Taken, dgClientTaken.CurrentRow.Cells["client_taken_id"].Value));
                    db.ExecuteNonQuery(string.Format(query.deleted_clientTaken, dgClientTaken.CurrentRow.Cells["client_taken_id"].Value));

                    // Delete zone record from list.
                    tblClientTaken.Select(string.Format("client_taken_id={0}", dgClientTaken.CurrentRow.Cells["client_taken_id"].Value))[0].Delete();
                }
            }
        }

        private void tblClientTaken_RowChanged(object sender, DataRowChangeEventArgs e)
        {
            btnCopy.Visible = tblClientTaken.Rows.Count > 0 ? true : false;
        }

        private void btnCopy_Click(object sender, EventArgs e)
        {
            _isCopy = true;
            dgClientTaken_CellDoubleClick(null, new DataGridViewCellEventArgs(0, dgClientTaken.SelectedRows[0].Index));
        }

        private void txtContStart_Validated(object sender, EventArgs e)
        {
            (new Libraies.ctl()).DateTimeTextBox(txtContStart, dtpContStart);
        }

        private void txtContEnd_Validated(object sender, EventArgs e)
        {
            (new Libraies.ctl()).DateTimeTextBox(txtContEnd, dtpContEnd);
        }

        private void dtpContStart_ValueChanged(object sender, EventArgs e)
        {
            txtContStart.Text = dtpContStart.Value.Date.ToString("dd/MM/yyyy");
        }

        private void dtpContEnd_ValueChanged(object sender, EventArgs e)
        {
            txtContEnd.Text = dtpContEnd.Value.Date.ToString("dd/MM/yyyy");
        }
    }
}
